{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# JS App Walkthrough\n",
    "\n",
    "> How to build a website with custom JavaScript in FastHTML step-by-step\n",
    "\n",
    "- order: 4\n",
    "- image: ./imgs/quickdraw.png"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Installation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You'll need the following software to complete the tutorial, read on for specific installation instructions:\n",
    "\n",
    "1. Python\n",
    "2. A Python package manager such as pip (which normally comes with Python) or uv\n",
    "3. FastHTML\n",
    "4. Web browser\n",
    "5. Railway.app account\n",
    "\n",
    "If you haven't worked with Python before, we recommend getting started with [Miniconda](https://docs.anaconda.com/miniconda/).\n",
    "\n",
    "Note that you will only need to follow the steps in the installation section once per environment. If you create a new repo, you won't need to redo these."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Install FastHTML"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For Mac, Windows and Linux, enter:\n",
    "\n",
    "```sh\n",
    "pip install python-fasthtml\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## First steps"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By the end of this section you'll have your own FastHTML website with tests deployed to railway.app."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create a hello world"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create a new folder to organize all the files for your project. Inside this folder, create a file called `main.py` and add the following code to it: \n",
    "\n",
    "```{.python filename=\"main.py\"}\n",
    "from fasthtml.common import *\n",
    "\n",
    "app = FastHTML()\n",
    "rt = app.route\n",
    "\n",
    "@rt('/')\n",
    "def get():\n",
    "    return 'Hello, world!'\n",
    "\n",
    "serve()\n",
    "```\n",
    "\n",
    "Finally, run `python main.py` in your terminal and open your browser to the 'Link' that appears."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### QuickDraw: A FastHTML Adventure 🎨✨"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The end result of this tutorial will be QuickDraw, a real-time collaborative drawing app using FastHTML. Here is what the final site will look like:\n",
    "\n",
    "![QuickDraw](imgs/quickdraw.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Drawing Rooms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Drawing rooms are the core concept of our application. Each room represents a separate drawing space where a user can let their inner Picasso shine. Here's a detailed breakdown:\n",
    "\n",
    "1. Room Creation and Storage\n",
    "\n",
    "```{.python filename=\"main.py\"}\n",
    "db = database('data/drawapp.db')\n",
    "rooms = db.t.rooms\n",
    "if rooms not in db.t:\n",
    "    rooms.create(id=int, name=str, created_at=str, pk='id')\n",
    "Room = rooms.dataclass()\n",
    "\n",
    "@patch\n",
    "def __ft__(self:Room):\n",
    "    return Li(A(self.name, href=f\"/rooms/{self.id}\"))\n",
    "```\n",
    "\n",
    "Or you can use our `fast_app` function to create a FastHTML app with a SQLite database and dataclass in one line:\n",
    "\n",
    "```{.python filename=\"main.py\"}\n",
    "def render(room):\n",
    "    return Li(A(room.name, href=f\"/rooms/{room.id}\"))\n",
    "\n",
    "app,rt,rooms,Room = fast_app('data/drawapp.db', render=render, id=int, name=str, created_at=str, pk='id')\n",
    "```\n",
    "We are specifying a render function to convert our dataclass into HTML, which is the same as extending the `__ft__` method from the `patch` decorator we used before. We will use this method for the rest of the tutorial since it is a lot cleaner and easier to read.\n",
    "\n",
    "* We're using a SQLite database (via FastLite) to store our rooms.\n",
    "* Each room has an id (integer), a name (string), and a created_at timestamp (string).\n",
    "* The Room dataclass is automatically generated based on this structure."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2. Creating a room\n",
    "\n",
    "```{.python filename=\"main.py\"}\n",
    "@rt(\"/\")\n",
    "def get():\n",
    "    # The 'Input' id defaults to the same as the name, so you can omit it if you wish\n",
    "    create_room = Form(Input(id=\"name\", name=\"name\", placeholder=\"New Room Name\"),\n",
    "                       Button(\"Create Room\"),\n",
    "                       hx_post=\"/rooms\", hx_target=\"#rooms-list\", hx_swap=\"afterbegin\")\n",
    "    rooms_list = Ul(*rooms(order_by='id DESC'), id='rooms-list')\n",
    "    return Titled(\"DrawCollab\", \n",
    "                  H1(\"DrawCollab\"),\n",
    "                  create_room, rooms_list)\n",
    "\n",
    "@rt(\"/rooms\")\n",
    "async def post(room:Room):\n",
    "    room.created_at = datetime.now().isoformat()\n",
    "    return rooms.insert(room)\n",
    "```\n",
    "\n",
    "* When a user submits the \"Create Room\" form, this route is called.\n",
    "* It creates a new Room object, sets the creation time, and inserts it into the database.\n",
    "* It returns an HTML list item with a link to the new room, which is dynamically added to the room list on the homepage thanks to HTMX."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "3. Let's give our rooms shape\n",
    "\n",
    "```{.python filename=\"main.py\"}\n",
    "@rt(\"/rooms/{id}\")\n",
    "async def get(id:int):\n",
    "    room = rooms[id]\n",
    "    return Titled(f\"Room: {room.name}\", H1(f\"Welcome to {room.name}\"), A(Button(\"Leave Room\"), href=\"/\"))\n",
    "```\n",
    "\n",
    "* This route renders the interface for a specific room.\n",
    "* It fetches the room from the database and renders a title, heading, and paragraph.\n",
    "\n",
    "\n",
    "Here is the full code so far:\n",
    "```{.python filename=\"main.py\"}\n",
    "from fasthtml.common import *\n",
    "from datetime import datetime\n",
    "\n",
    "def render(room):\n",
    "    return Li(A(room.name, href=f\"/rooms/{room.id}\"))\n",
    "\n",
    "app,rt,rooms,Room = fast_app('data/drawapp.db', render=render, id=int, name=str, created_at=str, pk='id')\n",
    "\n",
    "@rt(\"/\")\n",
    "def get():\n",
    "    create_room = Form(Input(id=\"name\", name=\"name\", placeholder=\"New Room Name\"),\n",
    "                       Button(\"Create Room\"),\n",
    "                       hx_post=\"/rooms\", hx_target=\"#rooms-list\", hx_swap=\"afterbegin\")\n",
    "    rooms_list = Ul(*rooms(order_by='id DESC'), id='rooms-list')\n",
    "    return Titled(\"DrawCollab\", create_room, rooms_list)\n",
    "\n",
    "@rt(\"/rooms\")\n",
    "async def post(room:Room):\n",
    "    room.created_at = datetime.now().isoformat()\n",
    "    return rooms.insert(room)\n",
    "\n",
    "@rt(\"/rooms/{id}\")\n",
    "async def get(id:int):\n",
    "    room = rooms[id]\n",
    "    return Titled(f\"Room: {room.name}\", H1(f\"Welcome to {room.name}\"), A(Button(\"Leave Room\"), href=\"/\"))\n",
    "\n",
    "serve()\n",
    "```\n",
    "\n",
    "Now run `python main.py` in your terminal and open your browser to the 'Link' that appears. You should see a page with a form to create a new room and a list of existing rooms."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### The Canvas - Let's Get Drawing! 🖌️"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Time to add the actual drawing functionality. We'll use Fabric.js for this:\n",
    "```{.python filename=\"main.py\"}\n",
    "# ... (keep the previous imports and database setup)\n",
    "\n",
    "@rt(\"/rooms/{id}\")\n",
    "async def get(id:int):\n",
    "    room = rooms[id]\n",
    "    canvas = Canvas(id=\"canvas\", width=\"800\", height=\"600\")\n",
    "    color_picker = Input(type=\"color\", id=\"color-picker\", value=\"#3CDD8C\")\n",
    "    brush_size = Input(type=\"range\", id=\"brush-size\", min=\"1\", max=\"50\", value=\"10\")\n",
    "    \n",
    "    js = \"\"\"\n",
    "    var canvas = new fabric.Canvas('canvas');\n",
    "    canvas.isDrawingMode = true;\n",
    "    canvas.freeDrawingBrush.color = '#3CDD8C';\n",
    "    canvas.freeDrawingBrush.width = 10;\n",
    "    \n",
    "    document.getElementById('color-picker').onchange = function() {\n",
    "        canvas.freeDrawingBrush.color = this.value;\n",
    "    };\n",
    "    \n",
    "    document.getElementById('brush-size').oninput = function() {\n",
    "        canvas.freeDrawingBrush.width = parseInt(this.value, 10);\n",
    "    };\n",
    "    \"\"\"\n",
    "    \n",
    "    return Titled(f\"Room: {room.name}\",\n",
    "                  canvas,\n",
    "                  Div(color_picker, brush_size),\n",
    "                  Script(src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js\"),\n",
    "                  Script(js))\n",
    "\n",
    "# ... (keep the serve() part)\n",
    "```\n",
    "\n",
    "Now we've got a drawing canvas! FastHTML makes it easy to include external libraries and add custom JavaScript."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Saving and Loading Canvases 💾"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we have a working drawing canvas, let's add the ability to save and load drawings. We'll modify our database schema to include a `canvas_data` field, and add new routes for saving and loading canvas data.\n",
    "Here's how we'll update our code:\n",
    "\n",
    "1. Modify the database schema:\n",
    "```{.python filename=\"main.py\"}\n",
    "app,rt,rooms,Room = fast_app('data/drawapp.db', render=render, id=int, name=str, created_at=str, canvas_data=str, pk='id')\n",
    "```\n",
    "\n",
    "2. Add a save button that grabs the canvas' state and sends it to the server:\n",
    "```{.python filename=\"main.py\"}\n",
    "@rt(\"/rooms/{id}\")\n",
    "async def get(id:int):\n",
    "    room = rooms[id]\n",
    "    canvas = Canvas(id=\"canvas\", width=\"800\", height=\"600\")\n",
    "    color_picker = Input(type=\"color\", id=\"color-picker\", value=\"#3CDD8C\")\n",
    "    brush_size = Input(type=\"range\", id=\"brush-size\", min=\"1\", max=\"50\", value=\"10\")\n",
    "    save_button = Button(\"Save Canvas\", id=\"save-canvas\", hx_post=f\"/rooms/{id}/save\", hx_vals=\"js:{canvas_data: JSON.stringify(canvas.toJSON())}\")\n",
    "    # ... (rest of the function remains the same)\n",
    "```\n",
    "\n",
    "3. Add routes for saving and loading canvas data:\n",
    "```{.python filename=\"main.py\"}\n",
    "@rt(\"/rooms/{id}/save\")\n",
    "async def post(id:int, canvas_data:str):\n",
    "    rooms.update({'canvas_data': canvas_data}, id)\n",
    "    return \"Canvas saved successfully\"\n",
    "\n",
    "@rt(\"/rooms/{id}/load\")\n",
    "async def get(id:int):\n",
    "    room = rooms[id]\n",
    "    return room.canvas_data if room.canvas_data else \"{}\"\n",
    "```\n",
    "\n",
    "4. Update the JavaScript to load existing canvas data:\n",
    "```{.javascript filename=\"main.py\"}\n",
    "js = f\"\"\"\n",
    "    var canvas = new fabric.Canvas('canvas');\n",
    "    canvas.isDrawingMode = true;\n",
    "    canvas.freeDrawingBrush.color = '#3CDD8C';\n",
    "    canvas.freeDrawingBrush.width = 10;\n",
    "    // Load existing canvas data\n",
    "    fetch(`/rooms/{id}/load`)\n",
    "    .then(response => response.json())\n",
    "    .then(data => {{\n",
    "        if (data && Object.keys(data).length > 0) {{\n",
    "            canvas.loadFromJSON(data, canvas.renderAll.bind(canvas));\n",
    "        }}\n",
    "    }});\n",
    "    \n",
    "    // ... (rest of the JavaScript remains the same)\n",
    "\"\"\"\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With these changes, users can now save their drawings and load them when they return to the room. The canvas data is stored as a JSON string in the database, allowing for easy serialization and deserialization.\n",
    "Try it out! Create a new room, make a drawing, save it, and then reload the page. You should see your drawing reappear, ready for further editing.\n",
    "\n",
    "Here is the completed code:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```{.python filename=\"main.py\"}\n",
    "from fasthtml.common import *\n",
    "from datetime import datetime\n",
    "\n",
    "def render(room):\n",
    "    return Li(A(room.name, href=f\"/rooms/{room.id}\"))\n",
    "\n",
    "app,rt,rooms,Room = fast_app('data/drawapp.db', render=render, id=int, name=str, created_at=str, canvas_data=str, pk='id')\n",
    "\n",
    "@rt(\"/\")\n",
    "def get():\n",
    "    create_room = Form(Input(id=\"name\", name=\"name\", placeholder=\"New Room Name\"),\n",
    "                       Button(\"Create Room\"),\n",
    "                       hx_post=\"/rooms\", hx_target=\"#rooms-list\", hx_swap=\"afterbegin\")\n",
    "    rooms_list = Ul(*rooms(order_by='id DESC'), id='rooms-list')\n",
    "    return Titled(\"QuickDraw\", \n",
    "                  create_room, rooms_list)\n",
    "\n",
    "@rt(\"/rooms\")\n",
    "async def post(room:Room):\n",
    "    room.created_at = datetime.now().isoformat()\n",
    "    return rooms.insert(room)\n",
    "\n",
    "@rt(\"/rooms/{id}\")\n",
    "async def get(id:int):\n",
    "    room = rooms[id]\n",
    "    canvas = Canvas(id=\"canvas\", width=\"800\", height=\"600\")\n",
    "    color_picker = Input(type=\"color\", id=\"color-picker\", value=\"#000000\")\n",
    "    brush_size = Input(type=\"range\", id=\"brush-size\", min=\"1\", max=\"50\", value=\"10\")\n",
    "    save_button = Button(\"Save Canvas\", id=\"save-canvas\", hx_post=f\"/rooms/{id}/save\", hx_vals=\"js:{canvas_data: JSON.stringify(canvas.toJSON())}\")\n",
    "\n",
    "    js = f\"\"\"\n",
    "    var canvas = new fabric.Canvas('canvas');\n",
    "    canvas.isDrawingMode = true;\n",
    "    canvas.freeDrawingBrush.color = '#000000';\n",
    "    canvas.freeDrawingBrush.width = 10;\n",
    "\n",
    "    // Load existing canvas data\n",
    "    fetch(`/rooms/{id}/load`)\n",
    "    .then(response => response.json())\n",
    "    .then(data => {{\n",
    "        if (data && Object.keys(data).length > 0) {{\n",
    "            canvas.loadFromJSON(data, canvas.renderAll.bind(canvas));\n",
    "        }}\n",
    "    }});\n",
    "    \n",
    "    document.getElementById('color-picker').onchange = function() {{\n",
    "        canvas.freeDrawingBrush.color = this.value;\n",
    "    }};\n",
    "    \n",
    "    document.getElementById('brush-size').oninput = function() {{\n",
    "        canvas.freeDrawingBrush.width = parseInt(this.value, 10);\n",
    "    }};\n",
    "    \"\"\"\n",
    "    \n",
    "    return Titled(f\"Room: {room.name}\",\n",
    "                  A(Button(\"Leave Room\"), href=\"/\"),\n",
    "                  canvas,\n",
    "                  Div(color_picker, brush_size, save_button),\n",
    "                  Script(src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js\"),\n",
    "                  Script(js))\n",
    "\n",
    "@rt(\"/rooms/{id}/save\")\n",
    "async def post(id:int, canvas_data:str):\n",
    "    rooms.update({'canvas_data': canvas_data}, id)\n",
    "    return \"Canvas saved successfully\"\n",
    "\n",
    "@rt(\"/rooms/{id}/load\")\n",
    "async def get(id:int):\n",
    "    room = rooms[id]\n",
    "    return room.canvas_data if room.canvas_data else \"{}\"\n",
    "\n",
    "serve()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Deploying to Railway"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can deploy your website to a number of hosting providers, for this tutorial we'll be using Railway. To get started, make sure you create an [account](https://railway.app/) and install the [Railway CLI](https://docs.railway.app/guides/cli). Once installed, make sure to run `railway login` to log in to your account.\n",
    "\n",
    "To make deploying your website as easy as possible, FastHTMl comes with a built in CLI tool that will handle most of the deployment process for you. To deploy your website, run the following command in your terminal in the root directory of your project:\n",
    "\n",
    "```sh\n",
    "fh_railway_deploy quickdraw\n",
    "```\n",
    "\n",
    "::: {.callout-note}\n",
    "Your app must be located in a `main.py` file for this to work.\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Conclusion: You're a FastHTML Artist Now! 🎨🚀"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Congratulations! You've just built a sleek, interactive web application using FastHTML. Let's recap what we've learned:\n",
    "\n",
    "1. FastHTML allows you to create dynamic web apps with minimal code.\n",
    "2. We used FastHTML's routing system to handle different pages and actions.\n",
    "3. We integrated with a SQLite database to store room information and canvas data.\n",
    "4. We utilized Fabric.js to create an interactive drawing canvas.\n",
    "5. We implemented features like color picking, brush size adjustment, and canvas saving.\n",
    "6. We used HTMX for seamless, partial page updates without full reloads.\n",
    "7. We learned how to deploy our FastHTML application to Railway for easy hosting.\n",
    "\n",
    "You've taken your first steps into the world of FastHTML development. From here, the possibilities are endless! You could enhance the drawing app further by adding features like:\n",
    "\n",
    "- Implementing different drawing tools (e.g., shapes, text)\n",
    "- Adding user authentication\n",
    "- Creating a gallery of saved drawings\n",
    "- Implementing real-time collaborative drawing using WebSockets\n",
    "\n",
    "Whatever you choose to build next, FastHTML has got your back. Now go forth and create something awesome! Happy coding! 🖼️🚀"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "jupytext": {
   "split_at_heading": true
  },
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
